package com.xoa.service.hr;

import com.xoa.dao.common.HrCodeMapper;
import com.xoa.dao.department.DepartmentMapper;

import com.xoa.dao.hr.HrphotoMapper;
import com.xoa.dao.users.UsersMapper;
import com.xoa.model.common.HrCode;
import com.xoa.model.common.HrCodeExample;
import com.xoa.model.enclosure.Attachment;

import com.xoa.model.hr.Hrphoto;
import com.xoa.model.hr.HrphotoWithBLOBs;
import com.xoa.model.users.Users;
import com.xoa.util.*;
import com.xoa.util.common.L;
import com.xoa.util.common.StringUtils;
import com.xoa.util.common.log.FileUtils;
import com.xoa.util.common.session.SessionUtils;
import com.xoa.util.common.wrapper.BaseWrapper;
import com.xoa.util.page.PageParams;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Row;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author 证照管理
 *        左春晖
 * @date 2018/7/3 13:22
 * @desc
 */
@Service
public class HrphotoService {

    @Resource
    HrphotoMapper hrphotoMapper;

    @Resource
    UsersMapper usersMapper;

    @Resource
    DepartmentMapper departmentMapper;

    @Autowired
    HrCodeMapper hrCodeMapper;





    /**
     * 添加
     */
    public ToJson addHrphoto(HttpServletRequest request,HrphotoWithBLOBs hrphotoWithBLOBs){
        ToJson json = new ToJson<>();
        Cookie redisSessionId = CookiesUtil.getCookieByName(request,"redisSessionId");
        Users user = SessionUtils.getSessionInfo(request.getSession(),Users.class,new Users(),redisSessionId);
        //创建者用户名
        hrphotoWithBLOBs.setCreateUserId(user.getUserId());
        //创建者部门编号
        hrphotoWithBLOBs.setCreateDeptId(user.getDeptId());
        //日期转换为 yyyy-dd-MM
        String staffName = hrphotoWithBLOBs.getStaffName();
        if (staffName.contains(",")) {
            String substring = staffName.substring(0, staffName.length() - 1);
            hrphotoWithBLOBs.setStaffName(substring);
        }
        hrphotoWithBLOBs.setCreateUserId(user.getUserName());
        hrphotoWithBLOBs.setCreateDeptId(user.getDeptId());
        hrphotoWithBLOBs.setAddTime(new Date());
        hrphotoWithBLOBs.setLastUpdateTime(new Date());
        hrphotoWithBLOBs.setGetLicenseDate(DateFormat.getDates(hrphotoWithBLOBs.getGetLicense()));
        hrphotoWithBLOBs.setEffectiveDate(DateFormat.getDates(hrphotoWithBLOBs.getEffective()));
       // hrphotoWithBLOBs.setExpireDate(DateFormat.getDates(hrphotoWithBLOBs.getExpireDates()));
        if(StringUtils.checkNull(hrphotoWithBLOBs.getAttachmentName())){
            hrphotoWithBLOBs.setAttachmentName("");
        }
        if (StringUtils.checkNull(hrphotoWithBLOBs.getExpirationPeriod())){
            hrphotoWithBLOBs.setExpirationPeriod("");
        }
        if (StringUtils.checkNull(hrphotoWithBLOBs.getStatus())){
            hrphotoWithBLOBs.setStatus("");
        }
        if (StringUtils.checkNull(hrphotoWithBLOBs.getAttachmentId())){
            hrphotoWithBLOBs.setAttachmentId("");
        }
        if (StringUtils.checkNull(hrphotoWithBLOBs.getRemark())){
            hrphotoWithBLOBs.setRemark("");
        }
        if (StringUtils.checkNull(hrphotoWithBLOBs.getRemindUser())){
            hrphotoWithBLOBs.setRemindUser("");
        }
        if (hrphotoWithBLOBs.getRemindType()==null){
            hrphotoWithBLOBs.setRemindType(0);
        }
        if (hrphotoWithBLOBs.getHasReminded()==null){
            hrphotoWithBLOBs.setHasReminded(0);
        }
        int temp = hrphotoMapper.insertSelective(hrphotoWithBLOBs);
        if (temp > 0) {
            json.setFlag(0);
            json.setMsg("success");
        } else {
            json.setFlag(1);
            json.setMsg("false");
        }
        return json;
    }

    /**
     * 修改
     */
    public ToJson upHrphoto(HrphotoWithBLOBs hrphotoWithBLOBs){
        ToJson json = new ToJson<>();
        int temp = hrphotoMapper.updateByPrimaryKeySelective(hrphotoWithBLOBs);
        if (temp > 0) {
            json.setFlag(0);
            json.setMsg("success");
        } else {
            json.setFlag(1);
            json.setMsg("false");
        }
        return json;
    }


    /**
     * 删除
     */
    public ToJson deleteHrphoto( String[] ids){
        ToJson json = new ToJson<>();
        int temp = hrphotoMapper.deleteByPrimaryKeys(ids);
        if (temp > 0) {
            json.setFlag(0);
            json.setMsg("success");
        } else {
            json.setFlag(1);
            json.setMsg("false");
        }
        return json;
    }

    /**
     * 查找
     */
    public ToJson<HrphotoWithBLOBs> selectHrphoto(HttpServletResponse response, HttpServletRequest request, HrphotoWithBLOBs hrphotoWithBLOBs, Integer page, Integer pageSize, boolean useFlag, String export) throws IllegalAccessException, NoSuchMethodException, InvocationTargetException, IOException {
        ToJson json = new ToJson<>();
        List<HrphotoWithBLOBs> list = new ArrayList<>();
        Map<String,Object> maps= new HashMap<>();
        PageParams pageParams = new PageParams();
        pageParams.setPage(page);
        pageParams.setPageSize(pageSize);
        pageParams.setUseFlag(useFlag);
        maps.put("page", pageParams);
        if(hrphotoWithBLOBs.getLicenseId()!=null){
            maps.put("licenseId",hrphotoWithBLOBs.getLicenseId());
        }
//        if(hrphotoWithBLOBs.getStaffName()!=null){
//            if (hrphotoWithBLOBs.getStaffName().contains(",")) {
//                String substring = hrphotoWithBLOBs.getStaffName().substring(0, hrphotoWithBLOBs.getStaffName().length() - 1);
//                hrphotoWithBLOBs.setStaffName(substring);
//                maps.put("staffName",hrphotoWithBLOBs.getStaffName());
//            }
//        }
        if(!StringUtils.checkNull(hrphotoWithBLOBs.getLicenseType())){
           maps.put("licenseType",hrphotoWithBLOBs.getLicenseType());
        }
        if (!StringUtils.checkNull(hrphotoWithBLOBs.getLicenseNo())){
            maps.put("licenseNo",hrphotoWithBLOBs.getLicenseNo());
        }
        if (!StringUtils.checkNull(hrphotoWithBLOBs.getLicenseName())){
            maps.put("licenseName",hrphotoWithBLOBs.getLicenseName());
        }
        if (!StringUtils.checkNull(hrphotoWithBLOBs.getStatus())){
            maps.put("status",hrphotoWithBLOBs.getStatus());
        }
        if (!StringUtils.checkNull(hrphotoWithBLOBs.getEffective())){
            maps.put("effectiveDate",hrphotoWithBLOBs.getEffective());
        }
        if (!StringUtils.checkNull(hrphotoWithBLOBs.getNotifiedBody())){
            maps.put("notifiedBody",hrphotoWithBLOBs.getNotifiedBody());
        }
        if (hrphotoWithBLOBs.getStaffName()!=null&& hrphotoWithBLOBs.getStaffName()!=""){
            //判断用户是否为空并转化字符串
            if(!StringUtils.checkNull(hrphotoWithBLOBs.getStaffName().toString())){
                String fromIds = hrphotoWithBLOBs.getStaffName().toString();
                String[] substring = fromIds.split(",");//分割
                maps.put("staffName",substring);
            }
        }
        list = hrphotoMapper.Allselect(maps);
        for (HrphotoWithBLOBs  hr :list){
           String username = usersMapper.getUsernameByUserId(hr.getStaffName());
           hr.setStaffName(username);

//            switch(hr.getLicenseType()){
//                case"1":
//                    hr.setLicenseType("驾驶证");
//                    break;
//                case "2":
//                    hr.setLicenseType("健康证");
//                    break;
//                case"3":
//                    hr.setLicenseType("暂住证");
//                    break;
//                case "4":
//                    hr.setLicenseType("技能证");
//                    break;
//
//                default:
//                    hr.setLicenseType("其他");
//                    break;
//            }
//            switch(hr.getStatus()){
//                case"1":
//                    hr.setStatus("未生效");
//                    break;
//                case "2":
//                    hr.setStatus("生效中");
//                    break;
//                case"3":
//                    hr.setStatus("已到期");
//                    break;
//            }
            //附件处理
            List<Attachment> attachmentList=new ArrayList<Attachment>();
            if(hr.getAttachmentName()!=null&&!"".equals(hr.getAttachmentName())){
                attachmentList= GetAttachmentListUtil.returnAttachment(hr.getAttachmentName(),hr.getAttachmentId(),"xoa" + (String) request.getSession().getAttribute("loginDateSouse"), "sdas");
            }
            hr.setAttachmentList(attachmentList);
        }



        if("1".equals(export)){//导出
            HSSFWorkbook workbook1 = ExcelUtil.makeExcelHead("证件照片信息", 9);
            String[] secondTitles = {"单位员工", "证照类型","证照编号","证照名称","状态","生效日期","到期日期","发证机构"};
            HSSFWorkbook workbook2 = ExcelUtil.makeSecondHead(workbook1, secondTitles);
            String[] beanProperty = {"staffName","licenseType","licenseNo","licenseName","status","effectiveDate2","expireDate3","notifiedBody"};
            SimpleDateFormat format0 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            for (HrphotoWithBLOBs  hr :list){

                if (!StringUtils.checkNull(hr.getEffectiveDate()+"")){
                    hr.setEffectiveDate2(format0.format(hr.getEffectiveDate()));
                }
                if (!StringUtils.checkNull(hr.getExpireDate()+"")){
                    hr.setExpireDate3(format0.format(hr.getEffectiveDate()));
                }
                if (hr.getStatus().equals("1")){
                    hr.setStatus("生效中");
                }
                if (hr.getStatus().equals("2")){
                    hr.setStatus("未生效");
                }
                if (hr.getStatus().equals("3")){
                    hr.setStatus("已到期");
                }
                //  1驾驶证.2健康证.3暂住证.4技能证.5其他
                if(hr.getLicenseType().equals("1")){
                    hr.setLicenseType("驾驶证");
                }
                if(hr.getLicenseType().equals("5")){
                    hr.setLicenseType("其他");
                }
                if(hr.getLicenseType().equals("2")){
                    hr.setLicenseType("健康证");
                }
                if(hr.getLicenseType().equals("3")){
                    hr.setLicenseType("暂住证");
                }
                if(hr.getLicenseType().equals("4")){
                    hr.setLicenseType("技能证");
                }
            }

            HSSFWorkbook workbook = ExcelUtil.exportExcelData(workbook2, list, beanProperty);
            ServletOutputStream out = response.getOutputStream();
            String filename = "证件照片信息.xls";
            filename = FileUtils.encodeDownloadFilename(filename, request.getHeader("user-agent"));
            response.setContentType("application/vnd.ms-excel");
            response.setHeader("content-disposition", "attachment;filename=" + filename);
            workbook.write(out);
            out.close();
        }
        json.setMsg("OK");
        json.setFlag(0);
        json.setTurn(true);
        json.setObj(list);
        json.setTotleNum(pageParams.getTotal());
        return json;
    }

    /**
     * @author 程叶同
     * @date 2018/7/23 16:33
     * @desc  人力资源系统代码表
     */
    private static final String HR_SCHOOL="HR_STAFF_LICENSE2";
    private static final String HR_DEGREE="HR_STAFF_LICENSE1";
    public BaseWrapper getHrCodes(String type){
        BaseWrapper baseWrapper=new BaseWrapper();
        List<HrCode> hrCodes=new ArrayList<>();
        HrCodeExample hrCodeExample=new HrCodeExample();
        HrCodeExample.Criteria criteria = hrCodeExample.createCriteria();
        hrCodeExample.setOrderByClause("cast(CODE_NO as SIGNED INTEGER) ASC");
        if ("edu".equals(type)) { //获取状态
            criteria.andParentNoEqualTo(HR_SCHOOL);
            hrCodes = hrCodeMapper.selectByExampleWithBLOBs(hrCodeExample);
        } else if ("degree".equals(type)) {//获取证照类型
        criteria.andParentNoEqualTo(HR_DEGREE);
        hrCodes=hrCodeMapper.selectByExampleWithBLOBs(hrCodeExample);
    }
        baseWrapper.setMsg("ok");
        baseWrapper.setFlag(true);
        baseWrapper.setData(hrCodes);
        baseWrapper.setStatus(true);
        return  baseWrapper;
    }

    //导入
    @SuppressWarnings("all")
    public ToJson<HrphotoWithBLOBs> imports(HttpServletRequest request, HttpServletResponse response, MultipartFile file) {
        ToJson<HrphotoWithBLOBs> json = new ToJson<HrphotoWithBLOBs>(1,"error");
        InputStream in=null;
        try {
            //判读当前系统
            //读取配置文件
            ResourceBundle rb = ResourceBundle.getBundle("upload");
            String osName = System.getProperty("os.name");
            StringBuffer path = new StringBuffer();
                 StringBuffer buffer=new StringBuffer();
        if(osName.toLowerCase().startsWith("win")){
            //sb=sb.append(rb.getString("upload.win"));
            //判断路径是否是相对路径，如果是的话，加上运行的路径
            String uploadPath = rb.getString("upload.win");
            if(uploadPath.indexOf(":")==-1){
                //获取运行时的路径
                String basePath = this.getClass().getClassLoader().getResource(".").getPath()+ File.pathSeparator;
                //获取截取后的路径
                String str2 = "";
                if(basePath.indexOf("/xoa")!=-1){
                    //获取字符串的长度
                    int length = basePath.length();
                    //返回指定字符在此字符串中第一次出现处的索引
                    int index = basePath.indexOf("/xoa");
                    //从指定位置开始到指定位置结束截取字符串
                    str2=basePath.substring(0,index);
                }
                path = path.append(str2 + "/xoa");
            }
            path.append(uploadPath);
            buffer=buffer.append(rb.getString("upload.win"));
        }else{
            path=path.append(rb.getString("upload.linux"));
            buffer=buffer.append(rb.getString("upload.linux"));
        }
            int success=0;
            // 判断是否为空文件
            if (file.isEmpty()) {
                json.setMsg("请上传文件！");
                json.setFlag(1);
                return json;
            } else {
                String fileName = file.getOriginalFilename();
                if (fileName.endsWith(".xls") || fileName.endsWith(".xlsx")) {
                    String uuid = UUID.randomUUID().toString().replaceAll("-", "");
                    int pos = fileName.indexOf(".");
                    String extName = fileName.substring(pos);
                    String newFileName = uuid + extName;
                    File dest = new File(path.toString(), newFileName);
                    file.transferTo(dest);
                    // 将文件上传成功后进行读取文件
                    // 进行读取的路径
                    String readPath = path.append(System.getProperty("file.separator")).append(newFileName).toString();
                    in = new FileInputStream(readPath);
                    HSSFWorkbook excelObj = new HSSFWorkbook(in);
                    HSSFSheet sheetObj = excelObj.getSheetAt(0);
                    Row row = sheetObj.getRow(0);
                    int colNum = row.getPhysicalNumberOfCells();
                    int lastRowNum = sheetObj.getLastRowNum();
                    HrphotoWithBLOBs hrphotoWithBLOBs = null;
                    for (int i = 2; i <= lastRowNum; i++) {
                        hrphotoWithBLOBs = new HrphotoWithBLOBs();
                        row = sheetObj.getRow(i);
                        String value = "";
                        if (row != null) {
                            for (int j = 0; j < colNum; j++) {
                                Cell cell = row.getCell(j);
                                if (cell != null) {
                                    switch (j) {
                                        case 0:
                                            // 用户名
                                            Users users = usersMapper.getUserByUserName(cell.getStringCellValue());
//                                            Department department = departmentMapper.getDeptById(users.getDeptId());
                                            hrphotoWithBLOBs.setCreateUserId(cell.getStringCellValue());
//                                            hrphotoWithBLOBs.setCreateDeptId(department.getDeptId());
                                            break;
                                        case 1:
                                            // 单位员工
                                            if (cell.getStringCellValue() != null) {
                                                Users user = usersMapper.getUserByUserName(cell.getStringCellValue());
                                                hrphotoWithBLOBs.setStaffName(user.getUserId());
                                            }
                                            break;
                                        case 2:
                                            //证照类型
                                            if(row.getCell(2)!=null){
                                                row.getCell(2).setCellType(CellType.STRING);
                                                hrphotoWithBLOBs.setLicenseType(row.getCell(2).getStringCellValue());
                                            }else {
                                                hrphotoWithBLOBs.setLicenseType(cell.getStringCellValue());
                                            }
                                            break;
                                        case 3:
                                            //证照编号
                                            if(row.getCell(3)!=null){
                                                row.getCell(3).setCellType(CellType.STRING);
                                                hrphotoWithBLOBs.setLicenseNo(row.getCell(3).getStringCellValue());
                                            }
//                                            hrphotoWithBLOBs.setLicenseNo(cell.getStringCellValue());
                                            break;
                                        case 4:
                                            //证照名称
                                            hrphotoWithBLOBs.setLicenseName(cell.getStringCellValue());
                                            break;
                                        case 5:
                                            // 取证日期
                                            if (cell.getCellType() == CellType.NUMERIC) {
                                                short format = cell.getCellStyle().getDataFormat();
                                                SimpleDateFormat sdf = null;
                                                if (format == 14 || format == 31 || format == 57 || format == 58) {
                                                    //日期
                                                    sdf = new SimpleDateFormat("yyyy-MM-dd");
                                                }
                                                double v = cell.getNumericCellValue();
                                                Date date = org.apache.poi.ss.usermodel.DateUtil.getJavaDate(v);
                                                hrphotoWithBLOBs.setGetLicenseDate(date);
                                                break;
                                            }
                                            hrphotoWithBLOBs.setGetLicenseDate(DateFormat.getDate(cell.getStringCellValue()));
                                            break;
                                        case 6:
                                            // 生效日期
                                            if (cell.getCellType() == CellType.NUMERIC) {
                                                short format = cell.getCellStyle().getDataFormat();
                                                SimpleDateFormat sdf = null;
                                                if (format == 14 || format == 31 || format == 57 || format == 58) {
                                                    //日期
                                                    sdf = new SimpleDateFormat("yyyy-MM-dd");
                                                }
                                                double v = cell.getNumericCellValue();
                                                Date date = org.apache.poi.ss.usermodel.DateUtil.getJavaDate(v);
                                                hrphotoWithBLOBs.setEffectiveDate(date);
                                                break;
                                            }
                                            hrphotoWithBLOBs.setGetLicenseDate(DateFormat.getDate(cell.getStringCellValue()));
                                            break;
                                        case 7:
                                            // 状态
                                            if(row.getCell(7)!=null){
                                                row.getCell(7).setCellType(CellType.STRING);
                                                hrphotoWithBLOBs.setStatus(row.getCell(7).getStringCellValue());
                                            }else {
                                                hrphotoWithBLOBs.setStatus(cell.getStringCellValue());
                                            }
                                            break;
                                        case 8:
                                            //是否限制期限
                                            hrphotoWithBLOBs.setExpirationPeriod(cell.getStringCellValue());
                                            break;
                                        case 9:
                                            // 到期日期
                                            if (cell.getCellType() == CellType.NUMERIC) {
                                                short format = cell.getCellStyle().getDataFormat();
                                                SimpleDateFormat sdf = null;
                                                if (format == 14 || format == 31 || format == 57 || format == 58) {
                                                    //日期
                                                    sdf = new SimpleDateFormat("yyyy-MM-dd");
                                                }
                                                double v = cell.getNumericCellValue();
                                                Date date = org.apache.poi.ss.usermodel.DateUtil.getJavaDate(v);
                                                hrphotoWithBLOBs.setExpireDate(date);
                                                break;
                                            }
                                            hrphotoWithBLOBs.setExpireDates(cell.getStringCellValue());
                                            break;
                                        case 10:
                                            // 发证机构
                                            hrphotoWithBLOBs.setNotifiedBody(cell.getStringCellValue());
                                            break;
                                        case 11:
                                            // 备注
                                            hrphotoWithBLOBs.setRemark(cell.getStringCellValue());
                                            break;
                                    }

                                }
                            }
                            if(hrphotoWithBLOBs!=null){
                                hrphotoWithBLOBs.setAddTime(new Date());
                                hrphotoWithBLOBs.setLastUpdateTime(new Date());
                                Cookie redisSessionId = CookiesUtil.getCookieByName(request,"redisSessionId");
                                Users user = SessionUtils.getSessionInfo(request.getSession(),Users.class,new Users(),redisSessionId);
                                //创建者用户名
                                hrphotoWithBLOBs.setCreateUserId(user.getUserId());
                                //创建者部门编号
                                hrphotoWithBLOBs.setCreateDeptId(user.getDeptId());
                                if(StringUtils.checkNull(hrphotoWithBLOBs.getStaffName())){
                                    hrphotoWithBLOBs.setStaffName("");
                                }
                                if(StringUtils.checkNull(hrphotoWithBLOBs.getAttachmentName())){
                                    hrphotoWithBLOBs.setAttachmentName("");
                                }
                                if(StringUtils.checkNull(hrphotoWithBLOBs.getLicenseType())){
                                    hrphotoWithBLOBs.setLicenseType("");
                                }
                                if (StringUtils.checkNull(hrphotoWithBLOBs.getLicenseNo())){
                                    hrphotoWithBLOBs.setLicenseNo("");
                                }
                                if (StringUtils.checkNull(hrphotoWithBLOBs.getLicenseName())){
                                    hrphotoWithBLOBs.setLicenseName("");
                                }
                                if (StringUtils.checkNull(hrphotoWithBLOBs.getStatus())){
                                    hrphotoWithBLOBs.setStatus("");
                                }
                                if (StringUtils.checkNull(hrphotoWithBLOBs.getNotifiedBody())){
                                    hrphotoWithBLOBs.setAttachmentName("");
                                }
                                if (StringUtils.checkNull(hrphotoWithBLOBs.getExpirationPeriod())){
                                    hrphotoWithBLOBs.setExpirationPeriod("");
                                }
                                if (StringUtils.checkNull(hrphotoWithBLOBs.getStatus())){
                                    hrphotoWithBLOBs.setStatus("");
                                }
                                if (StringUtils.checkNull(hrphotoWithBLOBs.getAttachmentId())){
                                    hrphotoWithBLOBs.setAttachmentId("");
                                }
                                if (StringUtils.checkNull(hrphotoWithBLOBs.getRemark())){
                                    hrphotoWithBLOBs.setRemark("");
                                }
                                if (StringUtils.checkNull(hrphotoWithBLOBs.getRemindUser())){
                                    hrphotoWithBLOBs.setRemindUser("");
                                }
                                if (hrphotoWithBLOBs.getRemindType()==null){
                                    hrphotoWithBLOBs.setRemindType(0);
                                }
                                if (hrphotoWithBLOBs.getHasReminded()==null){
                                    hrphotoWithBLOBs.setHasReminded(0);
                                }
                                if (StringUtils.checkNull(hrphotoWithBLOBs.getNotifiedBody())){
                                    hrphotoWithBLOBs.setNotifiedBody("");
                                }
                                int a =hrphotoMapper.insertSelective(hrphotoWithBLOBs);
                                if (a!=0){
                                    success = success + 1;
                                }
                            }

                        }
                    }
                }

            }
            HrphotoWithBLOBs temp=new HrphotoWithBLOBs();
            temp.setCount(success);
            json.setFlag(0);
            json.setMsg("ok");
            json.setObject(temp);
        } catch (Exception e) {
            e.printStackTrace();
            json.setMsg("数据保存异常");
            json.setFlag(1);
        } finally {
            try {
                if(in!=null){
                    in.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return json;
    }

    /**
     * 查询当前登陆用户数据
     *
     */
    public List<HrphotoWithBLOBs> getUserName(HttpServletRequest request,String userId){

        List<HrphotoWithBLOBs> list = hrphotoMapper.getHrStaffContractList(userId);
        for (HrphotoWithBLOBs  hr :list){
            String username = usersMapper.getUsernameByUserId(hr.getStaffName());
            hr.setStaffName(username);

//            switch(hr.getLicenseType()){
//                case"1":
//                    hr.setLicenseType("驾驶证");
//                    break;
//                case "2":
//                    hr.setLicenseType("健康证");
//                    break;
//                case"3":
//                    hr.setLicenseType("暂住证");
//                    break;
//                case "4":
//                    hr.setLicenseType("技能证");
//                    break;
//
//                default:
//                    hr.setLicenseType("其他");
//                    break;
//            }
//            switch(hr.getStatus()){
//                case"1":
//                    hr.setStatus("未生效");
//                    break;
//                case "2":
//                    hr.setStatus("生效中");
//                    break;
//                case"3":
//                    hr.setStatus("已到期");
//                    break;
//            }
            //附件处理
            List<Attachment> attachmentList=new ArrayList<Attachment>();
            if(hr.getAttachmentName()!=null&&!"".equals(hr.getAttachmentName())){
                attachmentList= GetAttachmentListUtil.returnAttachment(hr.getAttachmentName(),hr.getAttachmentId(),"xoa" + (String) request.getSession().getAttribute("loginDateSouse"), GetAttachmentListUtil.INCENTIVE);
            }
            hr.setAttachmentList(attachmentList);
        }
        return list;
    }

    /**
     * 创建者：戚中校
     * 方法作用：根据条件查询数量
     * @param
     * @param deptId(传入的多个部门的编号)
     * @return 返回的json字符串中  nums是返回的结果的数量
     *
     */
    public ToJson<Hrphoto> selectNumByCon(Hrphoto record, Integer[] deptId) {
        ToJson toJson = new ToJson();
        try {
            Map<String, Object> map = new HashMap<String, Object>();
            if (deptId != null && deptId.length > 0){
                map.put("deptId",deptId);
            }
            map.put("record",record);
            List<Hrphoto> list = hrphotoMapper.selectNumByCon(map);
            for(Hrphoto hrphoto:list) {
                if (!StringUtils.checkNull(hrphoto.getLicenseType())) {
                    switch (hrphoto.getLicenseType()) {
                        case "1":
                            hrphoto.setLicenseName("驾驶证");
                            break;
                        case "2":
                            hrphoto.setLicenseName("健康证");
                            break;
                        case "3":
                            hrphoto.setLicenseName("暂住证");
                            break;
                        case "4":
                            hrphoto.setLicenseName("技能证");
                            break;
                        case "":
                            hrphoto.setLicenseName("其它");
                            break;
                        default:
                            hrphoto.setLicenseName("其他");
                            break;
                    }
                }
                if (!StringUtils.checkNull(hrphoto.getStatus())) {
                    switch (hrphoto.getStatus()) {
                        case "1":
                            hrphoto.setStatusName("未生效");
                            break;
                        case "2":
                            hrphoto.setStatusName("生效中");
                            break;
                        case "3":
                            hrphoto.setStatusName("已到期");
                            break;
                        case "":
                            hrphoto.setStatusName("未知");
                            break;
                    }
                }
            }
            if(list.size() >= 0){
                toJson.setObj(list);
                toJson.setMsg("ok");
                toJson.setFlag(0);
            }else{
                toJson.setMsg("err");
                toJson.setFlag(1);
            }

        }catch (Exception e){
            toJson.setMsg("err");
            toJson.setFlag(1);
        }
        return toJson;
    }

    /**
     * 李阳
     * 2018.8.6
     * @param staffName
     * @return
     */
    public ToJson<HrphotoWithBLOBs> getByStaffName(String staffName, Integer page, Integer pageSize, boolean useFlag){
        ToJson<HrphotoWithBLOBs> json = new ToJson<HrphotoWithBLOBs>();
        //分页
        PageParams pageParams = new PageParams();
        pageParams.setPage(page);
        pageParams.setPageSize(pageSize);
        pageParams.setUseFlag(useFlag);
        HashMap<String,Object> map = new HashMap();
        map.put("pageParams", pageParams);
        map.put("staffName",staffName);
        try{
            List<HrphotoWithBLOBs> list=hrphotoMapper.getByStaffName(map);
            if(list.size()>0){
                for(HrphotoWithBLOBs photo:list){
                    Users user = usersMapper.findUsersByuserId(photo.getStaffName()); //根据 id 找名字
                    photo.setStaffName(user.getUserName());
                    //证件类型
                    HrCode hr_staff_contract2 = hrCodeMapper.selectCode("HR_STAFF_LICENSE1",photo.getLicenseType());
                    if (hr_staff_contract2 != null) {
                        photo.setLicenseType(hr_staff_contract2.getCodeName());
                    } else {
                        photo.setLicenseType(" ");
                    }
                }
                json.setObj(list);
            }
            json.setTotleNum(hrphotoMapper.getByStaffNameCount(staffName));
            json.setMsg("true");
            json.setFlag(0);
        }catch (Exception e){
            json.setMsg("err");
            json.setFlag(1);
        }
        return json;
    }
}
